<template>
  <div :class="[$style.container]">
    <div :class="[$style.header]">
      <el-link :underline="false" @click="onBack"><i class="el-icon-back ft-lg"></i></el-link>
      <span class="ml-3">重置密码</span>
    </div>
    <el-form :model="form" :rules="rules" ref="fm">
      <el-form-item prop="password" required>
        <el-input type="password" v-model.trim="form.password" placeholder="新密码" show-password></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" required>
        <el-input type="password" v-model.trim="form.confirmPassword" placeholder="确认密码"></el-input>
      </el-form-item>
    </el-form>

    <div :class="[$style.action]" class="mt-5">
      <el-button type="primary" :loading="submitting" @click="onSubmit" style="width: 100%;">提交</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Ref, Vue } from 'vue-property-decorator'
import { passwordValidator } from '@/config/validator'
import { changePasswordByCode } from '@/api/account'

@Component
export default class Step3 extends Vue {
  @Ref() fm!: any

  @Prop() stepData!: any

  submitting = false

  form = {
    password: '',
    confirmPassword: ''
  }

  get rules () {
    return {
      password: [
        { required: true, message: '请输入密码' },
        { validator: passwordValidator }
      ],
      confirmPassword: [
        { required: true, message: '请输入确认密码' },
        { validator: this.psCheckValidator }
      ]
    }
  }

  psCheckValidator (rule: any, value: any, callback: any) {
    if (!value) {
      callback()
    } else if (value !== this.form.password) {
      callback(new Error('两次输入密码不一致!'))
    } else {
      callback()
    }
  }

  onSubmit () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      this.submitting = true
      const req = {
        identifier: this.stepData.identifier,
        type: this.stepData.type,
        credential: this.stepData.code,
        newPassword: this.form.password
      }
      changePasswordByCode(req).then(() => {
        this.$message.success('密码重置成功')
        this.$router.replace('/login')
      }).finally(() => {
        this.submitting = false
      })
    })
  }

  onBack () {
    this.stepData.step = 2
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.header {
  margin-bottom: 12px;
  font-size: 16px;
}

.action {
  display: flex;
  justify-content: space-between;
}
</style>
